package cn.zch.soft.util.hutool.jdbc.connector;
import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.sql.SqlExecutor;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class Connector {
  private static final Log log = LogFactory.get();
  private Connector() {
  }
  public static void main(String[] args) {
    // 数据源工厂-DsFactory
    // 获取指定配置，第二个参数为分组，用于多数据源，无分组情况下传null
    // DataSource ds1 = DSFactory.get("group_db1")
    // DataSource ds2 = DSFactory.get("group_db2")
    // getTableMetaInfo(ds1)
    String string = "test中文";
    System.out.println(UnicodeUtil.toString("\u5fae\u4fe1\u652f\u4ed8(\u6d4b\u8bd5)"));
    System.out.println(UnicodeUtil.toUnicode(string));
  }
  private static void getTableMetaInfo(DataSource ds) {
    Log log = LogFactory.get();
    Connection conn = null;
    try {
      conn = ds.getConnection();
      // 执行非查询语句，返回影响的行数
      int count = SqlExecutor.execute(conn, "UPDATE TABLE_NAME set field1 = ? where id = ?", 0, 0);
      log.info("影响行数：{}", count);
      // 执行非查询语句，返回自增的键，如果有多个自增键，只返回第一个
      Long generatedKey = SqlExecutor.executeForGeneratedKey(conn, "UPDATE TABLE_NAME set field1 = ? where id = ?", 0, 0);
      log.info("主键：{}", generatedKey);

      /* 执行查询语句，返回实体列表，一个Entity对象表示一行的数据，Entity对象是一个继承自HashMap的对象，存储的key为字段名，value为字段值 */
      List<Entity> entityList = SqlExecutor.query(conn, "select * from TABLE_NAME where param1 = ?", new EntityListHandler(), "值");
      log.info("{}", entityList);
    }
    catch (SQLException e) {
      log.error(e.getMessage(), e, "SQL Error");
    }
    finally {
      DbUtil.close(conn);
    }
  }
}

